package com.evan.wj.service;

import com.evan.wj.dao.UserDAO;
import com.evan.wj.pojo.User;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserDAO userDAO;

    public boolean isExist(String username){
        User user=getByName(username);
        return null!=user;
    }

    public User getByName(String username){
        return userDAO.findByUsername(username);
    }

    public List<User> getAllByName(String username){
        return userDAO.findAllByUsernameLike('%' + username + '%' );
    }

    public User get(String username, String password){
        return userDAO.getByUsernameAndPassword(username, password);
    }

    public void add(User user){
        userDAO.save(user);
    }

    public void delete(User user){
        userDAO.delete(user);
    }

    public List<User> all(){
        List<User> all = userDAO.findAll();
        return all;
    }


    public int register(User user){
        String username = user.getUsername();

        String password = user.getPassword();

        username = HtmlUtils.htmlEscape(username);
        user.setUsername(username);

        user.setEnabled(true);

        if (username.equals("") || password.equals("")) {
            return 0;
        }

        boolean exist = isExist(username);

        if (exist) {
            return 2;
        }
//        // 默认生成 16 位盐
//        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
//        int times = 2;
//        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
//
//        user.setSalt(salt);
//        user.setPassword(encodedPassword);

        userDAO.save(user);

        return 1;
    }
}
